﻿using Cysharp.Threading.Tasks;
using UnityEngine;
using YooAsset;

namespace Client.Base
{
    public class FsmUpdatePackageManifest : PatchState
    {
        private bool isSucc = true;

        public FsmUpdatePackageManifest(PatchProcess procedure) : base(procedure)
        {
        }

        public override async void OnEnter()
        {
            this.Log("[Patch] FsmUpdatePackageManifest.");
            isSucc = true;
            var packages = YAPackageInfo.Setting.packages;
            for (int i = 0; i < packages.Length; i++)
                await UpdateManifest(packages[i].packageName);

            if (!isSucc)
            {
                Process.Call(Event_PatchError.EVENT_PATCHERROR, new Event_PatchError
                {
                    status = 1403,
                    message = $"更新资源清单失败 !"
                });
                return;
            }
            Process.TryTransition<FsmCreateDownloader>();
        }

        private async UniTask UpdateManifest(string packageName)
        {
            string packageVersion = Process.GetPackageVersion(packageName);
            var package = YooAssets.GetPackage(packageName);
            var operation = package.UpdatePackageManifestAsync(packageVersion);
            await operation.ToUniTask();

            if (operation.Status != EOperationStatus.Succeed)
            {
                isSucc = false;
                this.Log($"[Patch]: Fail ！-> pk:{packageName} , error : {operation.Error}");
            }
        }
    }
}

